package com.cloudbroker.bcs.common.mq.spring.converter;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.ContentTypeDelegatingMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;

public class TryJsonContentTypeDelegatingMessageConverter extends ContentTypeDelegatingMessageConverter {
    
    public TryJsonContentTypeDelegatingMessageConverter() {
        super(new DefaultContentTypeSimpleMessageConverter(MessageProperties.CONTENT_TYPE_TEXT_PLAIN));
    }
    
    public TryJsonContentTypeDelegatingMessageConverter(MessageConverter defaultConverter) {
        super(defaultConverter);
    }
    
    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) {
        if (null == object) {
            object = new byte[0];
        } else {
            object = JSON.toJSON(object);
            if (object instanceof JSON) {
                messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            } else if (ParserConfig.getGlobalInstance().isPrimitive(object.getClass())) {
                object = String.valueOf(object);
                messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
            }
        }
        return super.toMessage(object, messageProperties);
    }
    
}
